//
//  EmoticonKeyBoardView.swift
//  EmoticonKeyboard
//
//  Created by apple on 16/2/28.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit


private let EmoticonCellId = "EmoticonCellId"
private let toolBarHeight: CGFloat = 36

class EmoticonKeyBoardView: UIView {

    var emoticonManager = EmoticonManager.sharedEmoticoManager
    
    //可选类型
    var selectEmoticonCell: ((em: Emoticon) -> ())?
    
    //MARK: 按钮的监听方法
    @objc private func itemDidClick(item: UIBarButtonItem) {
        print(item.tag)
        //collectionView 设置滚动
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
    
    
    //重写构造方法
    init(selectEmoticon: (em: Emoticon) -> () ) {
        //记录闭包
        self.selectEmoticonCell = selectEmoticon
        let rect = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 220)
        super.init(frame: rect)
        self.backgroundColor = UIColor.redColor()
        setupUI()
    }
    
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        //添加子视图
        addSubview(toolbar)
        addSubview(collectionView)
        
        //设置约束
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.right.equalTo(self.snp_right)
            make.left.equalTo(self.snp_left)
            
            //默认的高度是44 
            make.height.equalTo(toolBarHeight)
        }
        
        //zai 初始化阶段 约束只是 被添加了
        //自动布局系统在这个阶段只是手机约束对象  在初始化阶段不会完成自动布局的操作
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            //1.设置底部约束 或者设置高度约束
            make.bottom.equalTo(toolbar.snp_top)
        }
        
        
        //设置工具条
        setToolBar()
        
        //设置toolbar tintColor
        toolbar.tintColor = UIColor.darkGrayColor()
        
    }
    
    
    private func setToolBar() {
        var items = [UIBarButtonItem]()
        
        
        //定义递增的 index
        var index = 0
        for p in emoticonManager.packages {
            
            
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
            
            let item = UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self, action: "itemDidClick:")
            items.append(item)
            item.tag = index++
            
            let space1 = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space1)
        }
        
        //设置标签按钮
        toolbar.items = items
    }
    //懒加载视图
    private lazy var toolbar = UIToolbar()
    
    private lazy var collectionView: UICollectionView = {
        
        let w = UIScreen.mainScreen().bounds.width / 7
        //设置 sectionInset
        //margin = (self.view.height - 36 - 3 * cellheight) / 4
        let margin = (self.bounds.height - toolBarHeight - 3 * w ) / 4
    
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: w, height: w)
        //设置滚动方向
        layout.scrollDirection = .Horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        cv.dataSource = self
        cv.delegate = self
        
        cv.backgroundColor = UIColor.whiteColor()
        //注册cell
        cv.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellId)
        cv.pagingEnabled = true
        return cv
    }()
    
    //自动布局真正生效 实在 布局子视图的时候才生效
    //1.addSubView  会调用 layoutSubViews
    //2.子视图的frame 发生该表的时候
    override func layoutSubviews() {
        super.layoutSubviews()
        //约束生效 实在 layoutSubView 结束之后才生效
        
        print(toolbar.bounds)
    }
}



//MARK: collectionView的数据源方法
extension EmoticonKeyBoardView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return emoticonManager.packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emoticonManager.packages[section].emoticonList.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellId, forIndexPath: indexPath) as! EmoticonCell
        //设置调试颜色
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.blueColor()
//        cell.emoticonBtn.setTitle("\(indexPath.section)\(indexPath.item)", forState: .Normal)
        cell.emoticon = emoticonManager.packages[indexPath.section].emoticonList[indexPath.item]
        return cell
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let em = emoticonManager.packages[indexPath.section].emoticonList[indexPath.item]
        selectEmoticonCell?(em: em)
    }
    
}


class EmoticonCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet {
            //使用绝对路径来加载图片
            print(emoticon?.imagePath)
            emoticonBtn.setImage(UIImage(contentsOfFile: emoticon?.imagePath ?? ""), forState: .Normal)
            emoticonBtn.setTitle(emoticon?.emojiStr ?? "", forState: .Normal)
            //如果是删除的模型 
            if let em = emoticon where em.isDelete {
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        //设置颜色
//        emoticonBtn.backgroundColor = UIColor.whiteColor()
        contentView.addSubview(emoticonBtn)
    
        //设置约束
        emoticonBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        //设置按钮的文字大小
        emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        //设置按钮不可交互
        emoticonBtn.userInteractionEnabled = false
    }
    
    //懒加载视图
    private lazy var emoticonBtn: UIButton = UIButton()
}
